package com.zhanglijie.theory.ArrayListDemo;

import java.awt.SystemColor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/7/21 0021 23:45
 */
public class SafeList {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        List<Integer> integers = Collections.synchronizedList(list);
        //修改操作
        new Thread(()->{
            for(int i=0;true;i++){
                integers.add(i);//add 方法会加锁
                integers.add(i+1);
                integers.remove(0);//remove也会加锁
            }
        }).start();
        //读操作
        new Thread(()->{
            synchronized (integers) {
                Iterator<Integer> iterator = integers.iterator();//尽管包装了但是迭代器不加锁。所以需要手动加上锁
                while (iterator.hasNext()) {
                    Integer next = iterator.next();
                    System.out.println(next);
                }
            }
        }).start();
    }
}
